#!/usr/bin/env python
# encoding: utf-8
'''
poc.TPlusAppSim -- TPlus App client simulation

poc.TPlusAppSim is a simulation App client of TPlus for testing.

It defines classes_and_methods

@author:     Anson Chan

@copyright:  2016 Xerland Co. Ltd. All rights reserved.

@contact:    anson_chan@xerland.com
@deffield    updated: Updated
'''
import sys
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
from Utils.SysConstants import SERVERAPI_CONFIGSERVICE
import json
import time
from Utils.JsonHelper import toJson
from Adb.MachModel import MachModel

def on_connect(mqttc, obj, flags, rc):
    print "Connected to %s:%s" % (mqttc._host, mqttc._port)

def on_message_power(mosq, obj, msg):
    # This callback will only be called for messages with topics that match
    # $SYS/broker/messages/#
    print("Power: "+msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_message_rtd(mosq, obj, msg):
    # This callback will only be called for messages with topics that match
    # $SYS/broker/bytes/#
    print("Rtd: "+msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    
def on_message(mqttc, obj, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_publish(mqttc, obj, mid):
    print("mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
    print(string)

# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client("10086")
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
mHostname = SERVERAPI_CONFIGSERVICE.getValue("mq_hostname")
mPort = int(SERVERAPI_CONFIGSERVICE.getValue("mq_port"))
mPowerSubUpdate = SERVERAPI_CONFIGSERVICE.getValue("mq_power_subscription_update")
mRtdSubUpdate = SERVERAPI_CONFIGSERVICE.getValue("mq_rtd_subscription_update")
mSubBase =  SERVERAPI_CONFIGSERVICE.getValue("mq_subscription_base")
mPowerSubRequest = SERVERAPI_CONFIGSERVICE.getValue("mq_power_subscription_request")
mRtdSubRequest = SERVERAPI_CONFIGSERVICE.getValue("mq_rtd_subscription_request")

mqttc.message_callback_add(mPowerSubUpdate, on_message_power)
mqttc.message_callback_add(mRtdSubUpdate, on_message_rtd)
mqttc.on_message = on_message
mqttc.connect(mHostname, mPort)
mqttc.subscribe(mSubBase, 0)

machReq = MachModel(0,"","2006-8-16 20:51:10", "2006-8-16 20:51:40")

rc = 0
while rc == 0:
    time.sleep(10)
    rc = mqttc.loop()
    mqttc.publish(mPowerSubRequest, json.dumps(machReq, default=toJson), 2)
    mqttc.publish(mRtdSubRequest, json.dumps(machReq, default=toJson), 2)
    

print("rc: "+str(rc))    
